﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;

namespace LINQToolKit
{
    public static class XmlExts
    {
        public static DateTime GetDateTime(this XAttribute source)
        {
            if (source == null || string.IsNullOrEmpty(source.Value))
            {
                return DateTime.MinValue;
            }

            return DateTime.Parse(source.Value);
        }

        public static bool GetBoolean(this XAttribute source)
        {
            if (source == null)
            {
                return false;
            }

            return Convert.ToBoolean(source.Value);
        }

        public static string GetString(this XAttribute source)
        {
            if (source == null)
            {
                return string.Empty;
            }

            return source.Value;
        }

        public static Type ToType(this XAttribute source)
        {
            return XmlExts.ToType(source, false);
        }

        public static Type ToType(this XAttribute source, bool throwOnErr)
        {
            if (source == null)
            {
                return null;
            }

            return Type.GetType(source.Value, throwOnErr);
        }

        public static int GetInt(this XAttribute source)
        {
            return XmlExts.GetInt(source, false);
        }

        public static int GetInt(this XAttribute source, bool throwOnErr)
        {
            if (source == null || string.IsNullOrEmpty(source.Value))
            {
                return int.MinValue;
            }

            return Convert.ToInt32(source.Value);
        }

        public static decimal GetDecimal(this XAttribute source)
        {
            return XmlExts.GetDecimal(source, false);
        }

        public static decimal GetDecimal(this XAttribute source, bool throwOnErr)
        {
            if (source == null || string.IsNullOrEmpty(source.Value))
            {
                return decimal.MinValue;
            }

            return Convert.ToDecimal(source.Value);
        }
    }
}
